package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.es.SkuESModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feigh.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.*;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class MallSearchServiceImpl implements MallSearchService {
    /**
     * @param param 检索的所有参数
     * @return 返回检索结果给页面
     */
    @Autowired
    private RestHighLevelClient client;
    @Autowired
   private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //动态构建查询DSL
        SearchResult result = null;
        //1。准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {//2.执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            //3.分析响应数据，封装成需要的响应数据
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * 封装检索结果
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        //1.返回所有查询到的商品

        SearchHits hits = response.getHits();
        //hits里面的
        List<SkuESModel> products = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuESModel skuESModel = new SkuESModel();
                skuESModel = JSON.parseObject(sourceAsString, SkuESModel.class);
                if(StringUtils.isNotEmpty(param.getKeyword())){
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    skuESModel.setSkuTitle(skuTitle);
                }
                products.add(skuESModel);
            }
            result.setProducts(products);
        }
        //2.查询到的商品涉及到的所有商品属性attrId,attrName,attrValue,从聚合中查询
         ParsedNested attr_agg=response.getAggregations().get("attr_agg");
        ParsedLongTerms attrId_agg=attr_agg.getAggregations().get("attrId_agg");
        List<SearchResult.AttrVo>attrs=new ArrayList<>();
        for (Terms.Bucket bucket : attrId_agg.getBuckets()) {
            //获取并设置attrId
            String attrId = bucket.getKeyAsString();
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(Long.parseLong(attrId));
            //获取并设置attrName
            ParsedStringTerms attr_name_agg=bucket.getAggregations().get("attr_name_agg");
            String attr_name = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name);
            //获取并设置attrValue
            ParsedStringTerms attr_value_agg=bucket.getAggregations().get("attr_value_agg");

             List<String> attrValue=attr_value_agg.getBuckets().stream().map(item->{
                         String keyAsString = item.getKeyAsString();
                         return keyAsString;
                     }).collect(Collectors.toList());
             attrVo.setAttrValue(attrValue);

             attrs.add(attrVo);
        }

       result.setAttrs(attrs);
        //3.查询到的商品涉及到的所有品牌信息
        // Long brandId;String brandName;String brandImg
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brands = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            //获取并设置catalogId
//            String brandId = bucket.getKeyAsString();
            long brandId = bucket.getKeyAsNumber().longValue();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
//            brandVo.setBrandId(Long.parseLong(brandId));
            brandVo.setBrandId(brandId);
            //获取并设置catalogName
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //获取并设置cbrandImg
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img);
            //
            brands.add(brandVo);
        }
        result.setBrands(brands);

        //4.查询到的商品涉及到的所有分类信息 catalogId catalogName
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        //不转换成ParsedLongTerms格式，就不能使用getBuckets方法。
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            //获取并设置catalogId
            String catalogId = bucket.getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(Long.parseLong(catalogId));
            //获取并设置catalogName
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogs.add(catalogVo);
        }
        result.setCatalogs(catalogs);
        //================以上信息要从聚合信息中查询到===================
        //5.分页信息

        result.setPageNum(param.getPageNum());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalPage = (int) (total % EsConstant.PRODUCT_PAGESIZE == 0 ? total /EsConstant.PRODUCT_PAGESIZE : (total / EsConstant.PRODUCT_PAGESIZE + 1));
        result.setTotalPages(totalPage);
        List<Integer>pageNavs=new ArrayList<>();
        for (int i = 1; i <=totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //6.面包屑导航功能

        if (param.getAttrs()!=null&&param.getAttrs().size()>0){
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map((attr) -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //arrts=2_华为，苹果  1.根据param获取属性名和值
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r=productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode()==0){
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                }else {
                    navVo.setNavValue(s[0]);
                }
                //2.取消面包屑以后，要跳转到哪个地方，将请求地址的url条件置空。拿到所有的查询条件，去掉当前。
                String replace = replaceQueryString(param, attr,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }
        //品牌
        if (param.getBrandId()!=null&& !param.getBrandId().isEmpty()){
            List<SearchResult.NavVo> navs=result.getNavs();
            SearchResult.NavVo navVo=new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //TODO 远程查询所有品牌
            R r = productFeignService.brandsInfo(param.getBrandId());
            if (r.getCode()==0){
                List<BrandVo> brandVos= r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer=new StringBuffer();
                String replace="";
                for (BrandVo brandVo : brandVos) {
                    buffer.append(brandVo.getName()+";");
                     replace=replaceQueryString(param,brandVo.getBrandId()+"","brandId");
                }
                navVo.setNavValue(buffer.toString());
                //set link
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
            }
            navs.add(navVo);
        }
        //TODO 分类,不需要导航取消
        if (param.getCatalog3Id()!=null){
            List<SearchResult.NavVo> navs=result.getNavs();
            SearchResult.NavVo navVo=new SearchResult.NavVo();
            navVo.setNavName("分类");
            //TODO 远程查询所有分类
            R r = productFeignService.catalogInfo(param.getCatalog3Id());
            if (r.getCode()==0){
                Catalog3Vo catalog3Vo = r.getData("data", new TypeReference<Catalog3Vo>() {
                });
                navVo.setNavValue(catalog3Vo.getName());
            }
            navs.add(navVo);
        }






        return result;
    }

    private static String replaceQueryString(SearchParam param, String value,String key) {
        String encode=null;
        try {
           encode= URLEncoder.encode(value,"UTF-8");
           encode=encode.replace("+","%20");//注意：浏览器空格编码为%20，JAVA编码为“+”

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String replace= param.getQueryString().replace("&"+key+"="+encode,"").replace(key+"="+encode,"");

        return replace;
    }

    /**
     * 准备检索请求
     * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询条件：过滤（按照属性，三级分类，品牌，价格区间，库存）
        //1、构建bool_query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must模糊匹配
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //1.2 filter -按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1.2 filter -按照brandId查询
        if (param.getBrandId() != null && !param.getBrandId().isEmpty()) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        //1.2 filter -按照所有指定的属性查询  &attrs=1_5寸：8寸&attrs=2_16G:8G
        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String[] attrValues = s[1].split(":");//检索的属性对应的值
                String arrtId = s[0];//检索的属性
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", arrtId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个属性都得生成一个nested查询。
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //1.2 filter -按照是否有库存进行查询  0:无库存，1：有库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        //1.2 filter -按照商品价格区间进行查询
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
//            1_500,_500,500_三种情况
            String[] price = param.getSkuPrice().split("_");
            if (price.length == 2) {
                //价格区间
                rangeQuery.gte(price[0]).lte(price[1]);
            }
            if (price.length == 1) {
                //_500或500_
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(price[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(price[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }


        sourceBuilder.query(boolQuery);
        //排序，分页，高亮，
        //2.1排序  skuPrice_asc/desc
        if (StringUtils.isNotEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //2.2分页
        /**
         * from 0,1,2,3,4;5 6 7 8 9
         * size 5
         * page 1          2
         * from=(page-1)*size
         */
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3高亮
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle").preTags("<b style='color:red'>").postTags("</b>");
            sourceBuilder.highlighter(builder);
        }


        //聚合分析
        //1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);

        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //3.属性聚合nested
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrId_agg = AggregationBuilders.terms("attrId_agg").field("attrs.attrId").size(50);
        attrId_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrId_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attrId_agg);
        sourceBuilder.aggregation(attr_agg);

        //把以前的所有条件进行封装
        sourceBuilder.query(boolQuery);
        System.out.println("请求的检索DSL:" + sourceBuilder);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
